package com.woncode.service;

import com.woncode.entity.RoleEntity;
import com.woncode.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Wang Guiwen on 2017/9/15.
 */
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserEntity userEntity = userService.findByName(s);
        return new User(userEntity.getName(), userEntity.getPassword(), getGrantedAuthoritySet(userEntity));
    }

    private Set<GrantedAuthority> getGrantedAuthoritySet(UserEntity userEntity) {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (RoleEntity r: userEntity.getRoles()){
            grantedAuthorities.add(new SimpleGrantedAuthority(r.getName()));
        }
        return grantedAuthorities;
    }
}
